﻿using Lcn_VoteSys.Models;
using Lcn_VoteSys.Models.Database;
using Lcn_VoteSys.service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Lcn_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : Controller
    {
        private readonly Lcn_VoteSysContext _db;
        private readonly IJWTService _jwtService;


        public UserController(Lcn_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }


        //注册
        /// <summary>
        /// 用户使用邮箱，密码进行注册，密码需要二次确认
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            //密码需要二次确认
            if (request.Password != request.CirPassword)
                return "两次密码输入不一致";

            //判断邮箱是否重复 拿这个邮箱 去数据库查 有没有存在
            if (_db.Users.Any(x => x.Email == request.Email))
                return "邮箱已存在";

            //把信息添加到数据库 注册成功
            _db.Users.Add(new User
            {
                Email = request.Email,
                Password = request.Password,
            });
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        //登录
        /// <summary>
        /// 用户使用邮箱，密码进行登录，登录后可访问需要授权的页面
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //1、使用邮箱去数据查询用户
            var user = _db.Users.FirstOrDefault(x => x.Email == request.Email);

            //2、判断是否空
            if (user == null)
                return "用户不存在";

            //3、判断密码是否正确
            if (user.Password != request.Password)
                return "密码不正确";

            //4、创建token
            return _jwtService.CreateToken(user.Id, user.Email);
        }
    }
}

